package com.qin.springbootdemo.dao;
import com.alibaba.fastjson.JSON;
import com.qin.springbootdemo.entity.cartlistEntity;
import com.qin.springbootdemo.entity.commodities;
import com.qin.springbootdemo.entity.swiper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;
import java.util.regex.Pattern;

/**
 * @author Leisure
 * create 2022 2022/6/18 10:22
 **/
@Repository
public class goodsDao {
    @Autowired
    private MongoTemplate mongoTemplate;

    //查询所有商品
    public List<commodities> findGoodsAll() {
        List<commodities> goods = mongoTemplate.findAll(commodities.class, "commodities");
        return goods;
    }
    //查询swiper
    public List<swiper> findSwiper(){
        List<swiper> swiper =  mongoTemplate.findAll(com.qin.springbootdemo.entity.swiper.class,"swiper");
        return swiper;
    }

    //查询具体商品名称，如苹果
    public List<commodities>  findSpecificGoods(String key) {
        Criteria criteria = new Criteria();
        String regex = String.format("%s%s%s", "^.*", key, ".*$");
        Pattern pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);
        criteria.orOperator(Criteria.where("goods.goodsTitle").regex(pattern));
        Query query = new Query(criteria);
        List<commodities> list = mongoTemplate.find(query, commodities.class);
        list.forEach(System.out::println);
        System.out.println("==================查询单个文档================");
        String qjddd = JSON.toJSONString(list);
        System.out.println(qjddd);
        return list;
    }

    //点击单个商品、通过id找到单个商品
    public commodities findGoodById(String id){
        commodities list = mongoTemplate.findById(id,commodities.class);
        return list;
    }



}
